package com.kds.changzhou.handler;

import com.kds.changzhou.data.Gateway;
import com.kds.changzhou.message.outboud.AbstractOutBoundMessage;
import com.kds.changzhou.netty.TcpClient;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.Attribute;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 孔德嵩
 */
@Slf4j
public class ConnectionStatusHandler extends ChannelInboundHandlerAdapter {


    public static final String CYAN = "\u001B[0;36m";
    public static final String RESET = "\u001B[0m";
    private HandlerConfig handlerConfig;

    public ConnectionStatusHandler(HandlerConfig handlerConfig) {
        this.handlerConfig = handlerConfig;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {


        AbstractOutBoundMessage message = handlerConfig.getOutBoundMessageFactory().buildRequestMessage();


        Attribute attr = ctx.channel().attr(TcpClient.GATE_WAY_KEY);
        Gateway gateway = (Gateway) attr.get();

        Map data = new HashMap<>();
        data.put("buildingCode", gateway.getBuildingCode());
        data.put("gatewayId", gateway.getGatewayId());
        message.setData(data);
        //写入对象
        ctx.writeAndFlush(message);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx, msg);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {


//        InetSocketAddress remoteAddress = (InetSocketAddress) ctx.channel().remoteAddress();
//        String ip = remoteAddress.getAddress().getHostAddress();
//        int port = remoteAddress.getPort();

        Attribute attr = ctx.channel().attr(TcpClient.GATE_WAY_KEY);

        Gateway gateway = (Gateway) attr.get();
        System.gc();
        TcpClient tcpClient = handlerConfig.createTcpClient(gateway);
        tcpClient.start();
    }


}
